package org.bing.engine.utility.codec;

import java.sql.Timestamp;
import java.util.Date;

public class PrimitiveJsonBase {
    public static final char OBJECT_BEG = '{';
    public static final char OBJECT_END = '}';
    public static final char ARRAY_BEG = '[';
    public static final char ARRAY_END = ']';
    public static final char OBJECT_FIELD_SPLIT = ',';
    public static final char FIELD_VALUE_SPLIT = ':';
    protected SimpleTypeHelper typeHelper = new SimpleTypeHelper();
    protected String nullString = "{null}";

    @SuppressWarnings({ "rawtypes" })
    public boolean isSupportedType(Class clazz) {
        if (clazz.isPrimitive()) {
            return true;
        }
        if (clazz == String.class || clazz == Date.class || Timestamp.class == clazz) {
            return true;
        }

        if (Boolean.class == clazz || Character.class == clazz || Byte.class == clazz || Short.class == clazz) {
            return true;
        }
        if (Integer.class == clazz || Long.class == clazz || Float.class == clazz || Double.class == clazz) {
            return true;
        }
        return false;
    }

    public boolean isSupportedType(String clzName) {
        try {
            if ("string".equals(clzName) || "date".equals(clzName)) {
                return true;
            } else if ("boolean".equals(clzName) || "char".equals(clzName) || "byte".equals(clzName) || "short".equals(clzName)
                    || "int".equals(clzName) || "long".equals(clzName) || "float".equals(clzName) || "double".equals(clzName)) {
                return true;
            } else {
                return isSupportedType(Class.forName(clzName));
            }
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    public boolean isBlank(String src) {
        if (src == null || src.trim().length() == 0) {
            return true;
        } else {
            return false;
        }
    }

    protected String primitiveObjectToString(Object obj) {
        if (obj instanceof Date) {
            return Long.toString(((Date) obj).getTime());
        } else if (obj instanceof String) {
            return escape((String) obj);
        } else {
            return obj.toString();
        }
    }

    private String escape(String src) {
        char[] chars = src.toCharArray();
        int len = chars.length;
        for (int i = 0; i < len; i++) {
            char c = chars[i];
            if (c == ',') {
                chars[i] = ' ';
            }
        }
        return new String(chars);
    }
}
